package com.xiang.seata.service;

import com.xiang.seata.feign.AccountFeignClient;
import com.xiang.seata.mapper.OrderMapper;
import com.xiang.seata.model.Order;
import io.seata.core.context.RootContext;
import io.seata.core.model.BranchType;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 */
@Slf4j
@Service
public class OrderService {
    @Resource
    private AccountFeignClient accountFeignClient;

    @Resource
    private OrderMapper orderMapper;

    //@Transactional(rollbackFor = Exception.class)
    @GlobalTransactional   // TM (Transaction Manager) - 事务管理器
    public void create(String userId, String commodityCode, Integer count) {
        String xid = RootContext.getXID();
        BranchType branchType = RootContext.getBranchType();
        boolean gloabTransaction = RootContext.inGlobalTransaction();
        log.info("全局事务ID：{}  --- 模式类型：{}  \n  是否在全局事务中：{}",xid,branchType,gloabTransaction);



        //订单金额
        Integer orderMoney = count * 2;

        Order order = new Order()
                .setUserId(userId)
                .setCommodityCode(commodityCode)
                .setCount(count)
                .setMoney(orderMoney);
        orderMapper.insert(order);

        accountFeignClient.reduce(userId, orderMoney);
    }
}
